package com.woyou.bean.rpc;

import com.google.gson.Gson;
import com.woyou.Constant;
import com.woyou.utils.DateUtils;
import com.woyou.utils.DesUtils;
import com.woyou.utils.MD5Utils;

import android.text.TextUtils;

/**
 * 请求加密实体
 * 
 * @author longtao.li
 * 
 */
public class MD5Req<T> {

	public MD5Req(T params) {
		this.params = params;
		md5();
	}

	public MD5Req(T params, String isEncrypted) {
		this.params = params;
		this.isEncrypted = isEncrypted;
		md5();
	}

	public T params; // 请求携带的数据

	public String jsonParams=""; // params的json字符串

	public String isEncrypted = "1"; // 是否加密

	public String timeStamp=""; // 时间戳

	public String randomNum = ""; // 随机数(6位)

	public String sign=""; // md5加密后的字符串

	// 计算方法：
	// MD5(Parameter+IsEncrypted+TimeStamp+RandomNum+MD5(Key))
	private void md5() { 
		if( TextUtils.isEmpty(timeStamp) ){
			timeStamp = DateUtils._getGMTime()+"";
		}
		while(randomNum.length()<6)
			randomNum+=(int)(Math.random()*10);
//		
		jsonParams = new Gson().toJson(params);
		jsonParams = jsonParams.replace(" ", "");
		
		if( isEncrypted.equals("1") ){
			try {
				jsonParams = DesUtils.encode(DesUtils.key, jsonParams);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		sign = jsonParams + isEncrypted + timeStamp +randomNum + MD5Utils.md5(Constant.IDELIVER_KEY);
		sign = MD5Utils.md5(sign);
	}

}
